package com.hpin.fansea.wxapi;

import android.content.Context;
import android.widget.Toast;

import com.tencent.mm.sdk.constants.Build;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

/**
 * 微信支付
 * 
 * @author Aaron
 */
public class WXPayEx {

	private IWXAPI wxapi;
	private Context context;

	public void initWXAPI(Context context) {
		this.context = context;
		wxapi = WXAPIFactory.createWXAPI(context, WXKeys.APP_ID);
		// 将该app注册到微信
		wxapi.registerApp(WXKeys.APP_ID);
	}

	/**
	 * 启动微信支付
	 * 
	 * @param
	 * @param tn
	 *            第三方支付返回的订单号
	 * @param nonceStr
	 *            支付平台的支付单号
	 * @param timeStamp
	 *            时间戳，为 1970 年 1 月 1 日 00:00 到请求发起时间的秒 数
	 * @param pkg
	 *            订单详情，对应微信字段package
	 * @param sign
	 *            签名，对应微信字段app_signature
	 */
	public void doStartWXPay(String tn, String nonceStr, String timeStamp,
			String pkg, String sign) {
		if (!wxapi.isWXAppInstalled()) {
			Toast.makeText(context, "请安装微信客户端！", Toast.LENGTH_SHORT).show();
			return;
		}

		boolean isPaySupported = wxapi.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;

//		LogUtil.e("tag", "isPaySupported===" + isPaySupported);

		if (isPaySupported) {

			PayReq req = new PayReq();
			req.appId = WXKeys.APP_ID;
			req.partnerId = WXKeys.PARTNER_ID;
			req.prepayId = tn;
			req.packageValue = pkg;
			req.nonceStr = nonceStr;
			req.timeStamp = timeStamp;
			req.sign = sign;

//			LogUtil.e("weixin", req.appId + "---" + req.partnerId + "---"
//					+ req.prepayId + "---" + req.nonceStr + "---"
//					+ req.timeStamp + "---" + req.packageValue + "---"
//					+ req.sign);

			// 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
			boolean b = wxapi.registerApp(WXKeys.APP_ID);

//			LogUtil.e("tag", "registerApp==" + b);

			boolean sendReq = wxapi.sendReq(req);

//			LogUtil.e("tag", "====sendReq====:" + sendReq);

		}
	}

}
